package com.zoweunion.mechanic.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zoweunion.mechanic.dao.PromotionCouponDao;
import com.zoweunion.mechanic.dao.base.MessageRecordDao;
import com.zoweunion.mechanic.entity.PromotionCouponEntity;
import com.zoweunion.mechanic.model.ResponseBean;
import com.zoweunion.mechanic.service.base.BaseService;
import com.zoweunion.mechanic.util.*;
import com.zoweunion.mechanic.util.constants.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zoweunion.mechanic.dao.UserCouponDao;
import com.zoweunion.mechanic.entity.UserCouponEntity;
import com.zoweunion.mechanic.service.UserCouponService;
import org.springframework.transaction.annotation.Transactional;


@Service("userCouponService")
public class UserCouponServiceImpl extends ServiceImpl<UserCouponDao, UserCouponEntity> implements UserCouponService {

    @Autowired
    private UserCouponDao userCouponDao;
    @Autowired
    private PromotionCouponDao promotionCouponDao;
    @Autowired
    private BaseService baseService;
    @Autowired
    private MessageRecordDao messageRecordDao;
    @Autowired
    private JiGuangPushUtil jiGuangPushUtil;


    @Override
    public PageInfo queryPage(Map<String, Object> map) {
        Integer pageSize = Integer.valueOf(map.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(map.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<UserCouponEntity> mapList = userCouponDao.queryPage(map);
        PageInfo<UserCouponEntity> mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void userCouponInsertUpdate(UserCouponEntity params) {
        userCouponDao.insert(params);
    }

    @Override
    public PromotionCouponEntity userCouponHead(Map<String, Object> params) {
        return userCouponDao.userCouponHead(params);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean giveCoupon(UserCouponEntity params) {
        Map<String, Object> map = userCouponDao.selectAccount(params.getMobilePhone());
        int giveList = userCouponDao.selectByList(params.getId());
        Map<String, Object> selectUnRegister = userCouponDao.selectUnRegister(params.getId());
        if (giveList>0||selectUnRegister!=null){
            return new ResponseBean(Constants.CODE_HANDEL_FAILED,
                    "领取失败,优惠券已被领取", "");
        }
        //更新优惠券为赠送
        userCouponDao.updateById(UserCouponEntity.builder()
                .id(params.getId())
                .useFlag(3)
                .build());
        if (map == null) {
            //todo 插入新表 注册时激活
            userCouponDao.insertUserGive(params);
            if (params.getGiveFlag()==1){
                return new ResponseBean(Constants.CODE_HANDEL_FAILED,
                        "对方未注册,邀请对方注册", "");
            }else if (params.getGiveFlag()==2){
                return new ResponseBean(Constants.CODE_HANDEL_FAILED,
                        "您尚未注册,请注册后领取", "");
            }
        } else {
            UserCouponEntity entity = userCouponDao.selectById(params.getId());
            String id = Orgin.getString(map, "id");
            params.setCouponId(entity.getCouponId());
            params.setGrantTime(entity.getGrantTime());
            params.setUserId(id);
            params.setUseFlag(1);//未使用
            params.setCouponSource(2);//好友赠送
            params.setGiveCouponId(params.getId());
            params.setCreateTime(new Date());
            userCouponDao.insert(params);
            String mobilePhone = userCouponDao.selectMobilePhone(params.getGiveUserId());
            //推送短信
            PromotionCouponEntity couponEntity = promotionCouponDao.selectById(entity.getCouponId());
            String contentgive = String.format(SmsUtil.couponpushgivesend,
                    mobilePhone.substring(0,3)
                    ,mobilePhone.substring(7,11)
                    ,couponEntity.getCouponMoney());
            SmsUtil.sendSms(params.getMobilePhone(),contentgive);
            //推送通知
            Map<String, Object> map1 = new HashMap<>();
            map1.put("s_id", "");
            map1.put("receive_user", id);
            map1.put("client", "YD");
            map1.put("id", UuidUtil.get32UUID());

            String pushTime = DateUtil.formatTime(LocalDateTime.now());
            String content = String.format(SmsUtil.couponpushgive, couponEntity.getCouponMoney());
            Map<String, Object> messageRecord = baseService.pushMessageCoupon(id,
                    pushTime, content);
            jiGuangPushUtil.publishMessagePush(messageRecord, "", "", id);
            map1.put("context", content);
            map1.put("send_type", 20);
            messageRecordDao.addMessageRecord(map1);
        }
        return new ResponseBean(Constants.CODE_SUCCESS,
                "已存入对方账户", "");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void getCouponByRegister(String userId, String mobilePhone) {
        List<Map<String, Object>> longs = userCouponDao.selectUserGive(mobilePhone);
        longs.forEach(item -> {
            long couponId = Orgin.getLongValue(item, "coupon_id");
            UserCouponEntity params = userCouponDao.selectById(couponId);
            params.setGrantTime(new Date());
            params.setUserId(userId);
            params.setUseFlag(1);//未使用
            params.setCouponSource(2);//好友赠送
            params.setGiveCouponId(params.getId());
            params.setGiveUserId(Orgin.getString(item, "give_user_id"));
            params.setCreateTime(new Date());
            userCouponDao.insert(params);
        });
        List<PromotionCouponEntity> entities = promotionCouponDao.selectCouponList();
        for (PromotionCouponEntity item : entities) {
            for (int i = 0; i < item.getSheet(); i++) {
                userCouponDao.insert(UserCouponEntity.builder()
                        .couponId(item.getId())
                        .userId(userId)
                        .grantTime(new Date())
                        .createTime(new Date())
                        .build());
            }
        }


    }

}